<template>
  <el-card>
    <el-form>
      <el-form-item label="角色名称">
        <el-input v-model="roleName" disabled />
      </el-form-item>
      <el-form-item label="权限列表">
        <!-- show-checkbox 展示多选框
        default-expand-all 默认展开
        -->
        <el-tree
          class="role-tree"
          :data="permissionList"
          show-checkbox
          default-expand-all
          :props="defaultProps"
          ref="treeRef"
          node-key="id"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="assignRolePermissionList">
          确定
        </el-button>
        <el-button @click="goRole">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqToAssign, reqDoAssign } from '@/api/role'

export default {
  name: 'RoleAuth',
  mounted() {
    const { id, roleName } = this.$route.query
    this.id = id
    this.roleName = roleName
    // console.log(this.$route.query);
    this.getToAssignList()
  },
  data() {
    return {
      id: undefined,
      roleName: '',
      permissionList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    async getToAssignList() {
      let result = await reqToAssign(this.id)
      // console.log(result);
      this.permissionList = result.data.children
      const selectKeys = this.getselectKeys(result.children)
      this.$refs.treeRef.setCheckedKeys(selectKeys)
    },

    // 获取选中的key
    getselectKeys(permission) {
      let selectKeysArr = []
      // console.log(permission.children);
      permission.forEach((permissionItem) => {
        if (permissionItem.children && permissionItem.children.length) {
          // 获取到选中的key
          const permissionChildren = this.getselectKeys(permissionItem.children)
          selectKeysArr = selectKeysArr.concat(permissionChildren)

          return
        }

        if (permissionItem.select) {
          // 判断是否被选中 如果被选中 直接往里面添加id值
          selectKeysArr.push(permissionItem.id)
        }
      })

      return selectKeysArr
    },
    goRole() {
      this.$router.push({
        name: 'Role'
      })
    },

    // 分配权限列表 发请求
    async assignRolePermissionList() {
      await reqDoAssign(this.id, [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ])
      this.$message.success('分配权限列表成功')
      this.goRole()
    }
  }
}
</script>

<style lang="less" scoped></style>
